<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\Receipt;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class ReceiptStatusForm extends Form
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $item = \App\Models\Receipt::find($input['id']);

        if (empty($item)) {
            return $this->response()->error('非法操作');
        }

        $item->status = $input['status'];
        $item->express_name = $input['status'] ? $input['express_name'] : '';
        $item->express_number = $input['status'] ? $input['express_number'] : '';
        $item->express_img = $input['status'] ? $input['express_img'] : '';
        $item->save();

        return $this
            ->response()
            ->success('操作成功')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->disableResetButton();
        $this->hidden('id');
        $this->select('status', '邮寄状态')
            ->options(Receipt::getStatusOptions())
            ->required()
            ->when(1, function (Form $form) {
                $this->select('express_name')->options(Receipt::getExpressNameOptions())->rules('required_if:status,1', ['required_if' => '请填写完整该项']);
                $this->text('express_number')->rules('required_if:status,1', ['required_if' => '请填写完整该项']);
                $this->file('express_img')->saveFullUrl()->autoUpload()->rules('required_if:status,1', ['required_if' => '请填写完整该项'])->saving(function ($path) {
                    return httpToHttps($path);
                });
            });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function
    default()
    {
        $row = $this->payload['row'] ?? null;
        if (!$row['status']) {
            return [
                'id' => $row['id']
            ];
        }
        return [
            'id'  => $row['id'],
            'status'  => $row['status'],
            'express_name'  => $row['express_name'],
            'express_number'  => $row['express_number'],
            'express_img'  => $row['express_img'],
        ];
    }
}
